﻿using System.Collections.Concurrent;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.SignalRHubs
{
    public class SignalRClientMapping : ISingletonDependency
    {
        private readonly ConcurrentDictionary<string, string> _dictionary =
          new ConcurrentDictionary<string, string>();

        private readonly ConcurrentDictionary<string, string> _reverseDictionary = new();

        public int Count => _dictionary.Count;

        public bool TryAdd(string clientName, string connectionId)
        {
            if (_dictionary.TryAdd(clientName, connectionId))
            {
                return _reverseDictionary.TryAdd(connectionId, clientName);
            }

            return false;
        }

        public bool TryGetConnectionId(string clientName, out string connectionId)
        {
            // TryGetValue 方法是线程安全的，并且尝试获取与指定键关联的值  
            return _dictionary.TryGetValue(clientName, out connectionId!);
        }

        public bool TryRemoveByConnectionId(string connectionId,out string? clientName)
        {
            if (_reverseDictionary.TryRemove(connectionId, out clientName))
            {
                return _dictionary.TryRemove(clientName, out _);
            }

            return false;
        }
    }
}
